﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SignalShopBase.Collections.DictionaryTree
{
    public class DictionaryTreeNode<T> : DictionaryTreeItem<T>
    {
        private Dictionary<string, DictionaryTreeItem<T>> items;

        public DictionaryTreeNode()
        {
            items = new Dictionary<string, DictionaryTreeItem<T>>();
        }

        public T Get(string key)
        {
            T result = default(T);

            if (key.Contains('/'))
            {
                string nodeName = key.Substring(0, key.IndexOf('/')).Trim();

                if (items.ContainsKey(nodeName))
                {
                    var item = items[nodeName];
                    if (item != null && item is DictionaryTreeNode<T>)
                    {
                        result = (item as DictionaryTreeNode<T>).Get(key.Substring(key.IndexOf('/') + 1));
                    }
                }
            }
            else
            {
                string leafName = key.Trim();

                if(items.ContainsKey(leafName))
                {
                    var item = items[leafName];
                    if(item != null && item is DictionaryTreeLeaf<T>)
                    {
                        result = (item as DictionaryTreeLeaf<T>).Item;
                    }
                }
            }

            return result;
        }

        public void Add(string key, T value)
        {
            if (key.Contains('/'))
            {
                string nodeName = key.Substring(0, key.IndexOf('/')).Trim();

                if (!items.ContainsKey(nodeName))
                {
                    var dtn = new DictionaryTreeNode<T>();
                    items.Add(nodeName, dtn);                    
                }

                ((DictionaryTreeNode<T>)items[nodeName]).Add(key.Substring(key.IndexOf('/') + 1), value);
            }
            else
            {
                string leafName = key.Trim();
                if (!items.ContainsKey(leafName))
                {
                    items.Add(leafName, new DictionaryTreeLeaf<T>(value));
                }
            }
        }
    }
}
